package li.nibble.twittertido;

import java.util.ArrayList;

import li.nibble.twittertido.adapter.TweetAdapter;
import li.nibble.twittertido.beans.Tweet;
import li.nibble.twittertido.model.DataBase;
import li.nibble.twittertido.view.PullToRefreshListView;
import li.nibble.twittertido.view.PullToRefreshListView.OnRefreshListener;
import li.nibble.twittertido.webservice.Client;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class HomeTab extends ListActivity {

	ArrayList<Tweet> tweets;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home);
		tweets = DataBase.getLocalTweet(this, DataBase.TABLE_HOME);

		TextView title = (TextView) findViewById(R.id.title);
		title.setText(getString(R.string.home));

		((PullToRefreshListView) getListView())
				.setOnRefreshListener(new OnRefreshListener() {
					@Override
					public void onRefresh() {
						new GetNewTweetsTaks().execute();
					}
				});

		TweetAdapter ta = new TweetAdapter(this, R.layout.tweet_row, tweets);
		setListAdapter(ta);
	}

	public class GetNewTweetsTaks extends AsyncTask<Void, Void, Void> {
		@Override
		protected Void doInBackground(Void... params) {
			// Simulates a background job.
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void voids) {

			if (li.nibble.twittertido.Utils.isOnline(HomeTab.this)) {

				ArrayList<Tweet> news_tweets = Client
						.getNewHome(getApplicationContext());
				tweets.addAll(0, news_tweets);
				TweetAdapter ta = new TweetAdapter(HomeTab.this,
						R.layout.tweet_row, tweets);
				DataBase.insertLocalTweets(getApplicationContext(),
						news_tweets, DataBase.TABLE_HOME);
				setListAdapter(ta);
				// Call onRefreshComplete when the list has been refreshed.
				((PullToRefreshListView) getListView()).onRefreshComplete();
			} else {
				Toast.makeText(getApplicationContext(), getApplicationContext()
						.getString(R.string.no_connected), Toast.LENGTH_SHORT);
			}
			super.onPostExecute(voids);

		}
	}

}
